package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.base.enums.ResultCodeEnum;
import com.uinnova.product.eam.base.exception.ServerException;
import com.uinnova.product.eam.base.util.EamUtil;
import com.uinnova.product.eam.comm.model.CListType;
import com.uinnova.product.eam.comm.model.ListType;
import com.uinnova.product.eam.service.IListTypeSvc;
import com.uinnova.product.eam.service.es.ListTypeDao;
import com.uino.bean.permission.base.SysUser;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 王春蕾
 */
@Service
public class ListTypeSvcImpl implements IListTypeSvc {

    @Resource
    private ListTypeDao listTypeDao;

    @Override
    public Integer saveOrUpdateListType(List<CListType> listTypes) {
        SysUser userInfo = SysUtil.getCurrentUserInfo();
        //重名校验；
        Set<String> typeNames = listTypes.stream().map(CListType::getTypeName).collect(Collectors.toSet());
        if (typeNames.size() != listTypes.size()) {
            throw new ServerException("清单类型名称不能重复");
        }
        //存量数据的删除
        List<Long> ids = listTypes.stream().map(CListType::getId).filter(Objects::nonNull).collect(Collectors.toList());
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.mustNot(QueryBuilders.termsQuery("id",ids.toArray()));
        listTypeDao.deleteByQuery(boolQueryBuilder,true);

        //批量新增
        List<ListType> types = new ArrayList<>();
        for (CListType listType : listTypes) {
            long uuid = ESUtil.getUUID();
            if (BinaryUtils.isEmpty(listType.getId())) {
                listType.setId(uuid);
                listType.setCreator(userInfo.getLoginCode());
            }
            ListType type = EamUtil.copy(listType, ListType.class);
            type.setDomainId(userInfo.getDomainId());
            types.add(type);
        }
        return listTypeDao.saveOrUpdateBatch(types);
    }

    @Override
    public Integer deleteListingType(Long id) {
        return listTypeDao.deleteById(id);
    }


    @Override
    public List<ListType> queryListTypes() {
        CListType type = new CListType();
        List<ListType> lists = listTypeDao.getListByCdt(type);
        if (lists == null || lists.isEmpty()) {
            return new ArrayList<>();
        }else{
            return lists.stream().sorted(Comparator.comparing(ListType::getSort)).collect(Collectors.toList());
        }
    }

}
